package com.snails.permission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.snails.permission.iface.IPermission;
import com.snails.permission.util.PermissionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lawrence
 * @date 2019-05-05 16:25
 */
public class PermissionRequestActivity extends Activity {

    private static IPermission sPermissionListener = null;
    private static final String PERMISSION_KEY = "permission_key";
    private static final String REQUEST_CODE = "request_code";

    private String[] permissions;
    private int requestCode;

    /**
     * 跳转到Activity申请权限
     */
    public static void PermissionRequest(Context ctx,
                                 String[] permissions, int requestCode, IPermission iPermission) {
        if (ctx != null && permissions != null
                && permissions.length > 0 && iPermission != null) {
            sPermissionListener = null;
            final boolean result = hasSelfPermissions(ctx, permissions, iPermission);
            if (!result) {
                sPermissionListener = iPermission;
                jump2PermissionRequest(ctx, permissions, requestCode, iPermission);
                // 禁止activity切换动画
                if (ctx instanceof Activity) {
                    Activity act = (Activity) ctx;
                    if (act != null) {
                        act.overridePendingTransition(0, 0);
                    }
                }
            }
        }
    }

    /**
     * 初步检查权限是否都已授予
     */
    private static boolean hasSelfPermissions(Context ctx, String[] permissions, IPermission iPermission) {
        final boolean result = PermissionUtil.hasSelfPermissions(ctx, permissions);
        if (result) { // 已授予全部权限
            if (iPermission != null) iPermission.PermissionGranted();
        }
        return result;
    }

    /**
     * 跳转权限申请activity
     */
    private static void jump2PermissionRequest(Context ctx,
                               String[] permissions, int requestCode, IPermission iPermission) {
        Intent intent = new Intent(ctx, PermissionRequestActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putStringArray(PERMISSION_KEY, permissions);
        bundle.putInt(REQUEST_CODE, requestCode);
        intent.putExtras(bundle);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!setRootContentView().getBundleParams(savedInstanceState)) return;
        requestPermission(permissions);
    }

    // 设置布局
    private PermissionRequestActivity setRootContentView() {
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.setBackgroundResource(R.color.colorTransparent);
        FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        setContentView(frameLayout, frameLayoutParams);
        return this;
    }

    // 获得参数
    private boolean getBundleParams(@Nullable Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            permissions = bundle.getStringArray(PERMISSION_KEY);
            requestCode = bundle.getInt(REQUEST_CODE, 0);
        }
        return permissions != null && permissions.length > 0;
    }

    /**
     * 申请权限
     */
    private void requestPermission(String[] permissions) {
        if (hasSelfPermissions(this, permissions, sPermissionListener)) {
            finishSelf();
        } else {
            // 权限申请
            ActivityCompat.requestPermissions(this, permissions, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PermissionUtil.verifyPermissions(grantResults)) {
            //所有权限都同意
            if (sPermissionListener != null) sPermissionListener.PermissionGranted();
        } else {
            if (!PermissionUtil.shouldShowRequestPermissionRationale(this, permissions)) {
                //权限被拒绝并且选中不再提示
                if (permissions.length != grantResults.length) return;
                List<String> denyList = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == -1) denyList.add(permissions[i]);
                }
                if (sPermissionListener != null) sPermissionListener.PermissionDenied(requestCode, denyList);
            } else {
                //权限被取消
                if (sPermissionListener != null) sPermissionListener.PermissionCanceled(requestCode);
            }

        }
        finishSelf();   // 关闭页面
    }

    /**
     * 关闭本页面
     */
    private void finishSelf() {
        sPermissionListener = null;
        finish();
        overridePendingTransition(0, 0);
    }

}
